<?php

namespace haibao\cms\data\starpk;

use haibao\cms\model\filter\starpk\StarPkDefine as StarPkDefineFilter;
use haibao\cms\model\filter\starpk\StarPkCelebrity as StarPkCelebrityFilter;

class StarPkDefine extends \haibao\cms\data\BaseMysql{

    public function __construct(){
        parent::__construct('\haibao\cms\model\data\starpk\StarPkDefine');
    }
    
    public function addStarPk($addStarPkModel){
        $this->beginTranscation();
        try{
            $this->add($addStarPkModel);
            $this->addStarPkCelebrity($addStarPkModel);
            $this->addStarPkProduct($addStarPkModel);
        } catch(\Exception $e){
            throw $e;
        }
        $this->endtranscation();
        return $addStarPkModel;
    }
    
    public function updatStarPkListById($editStarPkModel){
        $starPkDefineModel = $this->packStarPkDefine($editStarPkModel);
        $this->beginTranscation();
        try{
            $this->updateById($editStarPkModel->Id,$starPkDefineModel);
            $this->updateStarPkCelebrityData($editStarPkModel);
            $this->updateStarPkProductData($editStarPkModel);
        } catch(\Exception $e){
            throw $e;
        }
        $this->endtranscation();
    }
    
    public function delStarPkListById($id,$status){
        $this->updateById($id, $status);
    }

    public function updateStarPkProductNumById($starPkId){
    	$sql = "update StarPkDefine set StarLikeNum=StarLikeNum-1 where Id=%s";
    	$this->query($sql,array($starPkId));
    }
    Public function updateProductSort($Id,$key){
    	$sql = "update StarPkProduct set SortNum=$key where Id=%s";
    	$this->query($sql,array($Id));
    }
    
    public function getPublishInfoByIds($published=\haibao\cms\model\data\starpk\StarPkDefine::PUBLISHED_ING){
    	$ids = array();
    	if($published == \haibao\cms\model\data\starpk\StarPkDefine::PUBLISHED_PRE){
    		$date = date('Y-m-d H:i:s');
    		$sql="select Id from StarPkDefine where Published = %s and PublishTime <=%s and Status=%s order by Id DESC";
    		$result = $this->query($sql,array($published,$date,\haibao\cms\model\data\starpk\StarPkDefine::STARUS_OK));
    	}else{
    		$sql="select Id from StarPkDefine where Published = %s and Status=%s order by Id DESC";
    		$result = $this->query($sql,array($published,\haibao\cms\model\data\starpk\StarPkDefine::STARUS_OK));
    	}
    	while($result->fetch_assoc()){
    		array_push($ids,$result->getData('Id'));
    	}
    	return $ids;
    }
    public function updateStarPkPublished($id){

    	$sql="update StarPkDefine set Published=%s where Id=%s";
    	$this->query($sql,array(\haibao\cms\model\data\starpk\StarPkDefine::PUBLISHED_YES,$id));
    }
    
    private function addStarPkCelebrity($addStarPkModel){
    	$starPkCelebrityModel = new \haibao\cms\model\data\starpk\StarPkCelebrity();
    	foreach($addStarPkModel->StarPkCelebrity->CelebrityId as $key=>$value){
    		$starPkCelebrityModel->StarPkId = $addStarPkModel->Id;
    		$starPkCelebrityModel->CelebrityId = $addStarPkModel->StarPkCelebrity->CelebrityId[$key];
    		$starPkCelebrityModel->PicUrl =$addStarPkModel->StarPkCelebrity->PicUrl[$key];
    		$starPkCelebrityModel->PicSource = $addStarPkModel->StarPkCelebrity->PicSource[$key];
    		$starPkCelebrityModel->CelebrityDesc = $addStarPkModel->StarPkCelebrity->CelebrityDesc[$key];
    		$starPkCelebrityModel->SortNum =$key;
    		$starPkCelebrityModel->CelebrityVoteNum = $addStarPkModel->StarPkCelebrity->CelebrityVoteNum;
    		$starPkCelebrityModel->CreateTime = $addStarPkModel->StarPkCelebrity->CreateTime;
    		$this->add($starPkCelebrityModel);
    	}
    }
    
    private function addStarPkProduct($addStarPkModel){
    	foreach ($addStarPkModel->StarPkProduct as $value){
    		$value->StarPkId = $addStarPkModel->Id;
    	}
    
    	$starPkProductModel = new \haibao\cms\data\starpk\StarPkProduct();
    	$starPkProductModel->addAll($addStarPkModel->StarPkProduct);
    }
    
    private function packStarPkDefine($editStarPkModel){
    	$StarPkDefineFilter =  new StarPkDefineFilter();
    	$starPkDefine = array(
    			StarPkDefineFilter::CONDITION_FIELD_NAME_TITLE => $editStarPkModel->Title,
    			StarPkDefineFilter::CONDITION_FIELD_NAME_STAR_NUM => $editStarPkModel->StarNum,
    			StarPkDefineFilter::CONDITION_FIELD_NAME_STAR_LIKE_NUM => $editStarPkModel->StarLikeNum,
    			StarPkDefineFilter::CONDITION_FIELD_NAME_STATUS => $editStarPkModel->Status,
    			StarPkDefineFilter::CONDITION_FIELD_NAME_PUBLISHED => $editStarPkModel->Published,
    			StarPkDefineFilter::CONDITION_FIELD_NAME_MODEL_PIC => $editStarPkModel->ModelPic,
    			StarPkDefineFilter::CONDITION_FIELD_NAME_BRAND_ID => $editStarPkModel->BrandId,
    			StarPkDefineFilter::CONDITION_FIELD_NAME_CREATE_BY => $editStarPkModel->CreateBy,
    			StarPkDefineFilter::CONDITION_FIELD_NAME_EDITOR => $editStarPkModel->Editor,
    			StarPkDefineFilter::CONDITION_FIELD_NAME_IS_PSEUDONYM => $editStarPkModel->IsPseudonym,
    			StarPkDefineFilter::CONDITION_FIELD_NAME_PUBLISH_TIME => $editStarPkModel->PublishTime,
    			StarPkDefineFilter::CONDITION_FIELD_NAME_CREATE_TIME => $editStarPkModel->CreateTime,
    	);
    
    	return $starPkDefine;
    }
    
    private function updateStarPkCelebrityData($editStarPkModel){
    	$starPkCelebrityData = new \haibao\cms\data\starpk\StarPkCelebrity();
    
    	$starPkCelebrityFilter = new StarPkCelebrityFilter();
    	$starPkCelebrityFilter->select(array(
    			StarPkCelebrityFilter::CONDITION_FIELD_NAME_ID,
    			StarPkCelebrityFilter::CONDITION_FIELD_NAME_STAR_PK_ID,
    	));
    
    	$starPkCelebrityFilter->where($starPkCelebrityFilter::CONDITION_FIELD_NAME_STAR_PK_ID,\haibao\frame\data\query\Condition::CONDITION_EQUAL, $editStarPkModel->Id);
    	$starPkCelebrityList = $this->getAll($starPkCelebrityFilter);
    
    	$celebrityIdArr = array();
    	foreach($starPkCelebrityList as $type){
    		$celebrityIdArr[] = $type->Id;
    	}
    
    	if($editStarPkModel->StarPkCelebrity->CelebrityId){
    		foreach($editStarPkModel->StarPkCelebrity->CelebrityId as $key=>$value){
    			$starPkCelebrityFilter = new StarPkCelebrityFilter();
    			$starPkCelebrityFilter->where($starPkCelebrityFilter::CONDITION_FIELD_NAME_ID,\haibao\frame\data\query\Condition::CONDITION_EQUAL, $celebrityIdArr[$key]);
    			$starPkCelebrity = array(
    					StarPkCelebrityFilter::CONDITION_FIELD_NAME_STAR_PK_ID => $editStarPkModel->Id,
    					StarPkCelebrityFilter::CONDITION_FIELD_NAME_CELEBRITY_ID => $editStarPkModel->StarPkCelebrity->CelebrityId[$key],
    					StarPkCelebrityFilter::CONDITION_FIELD_NAME_PIC_URL =>$editStarPkModel->StarPkCelebrity->PicUrl[$key],
    					StarPkCelebrityFilter::CONDITION_FIELD_NAME_PIC_SOURCE => $editStarPkModel->StarPkCelebrity->PicSource[$key],
    					StarPkCelebrityFilter::CONDITION_FIELD_NAME_CELEBRITY_DESC => $editStarPkModel->StarPkCelebrity->CelebrityDesc[$key],
    					StarPkCelebrityFilter::CONDITION_FIELD_NAME_SORT_NUM =>$key,
    					StarPkCelebrityFilter::CONDITION_FIELD_NAME_CELEBRITY_VOTE_NUM => $editStarPkModel->StarPkCelebrity->CelebrityVoteNum,
    					StarPkCelebrityFilter::CONDITION_FIELD_NAME_CREATE_TIME => $editStarPkModel->StarPkCelebrity->CreateTime,
    
    			);
    			$starPkCelebrityData->update($starPkCelebrity,$starPkCelebrityFilter);
    		}
    	}
    }
    private function updateStarPkProductData($editStarPkModel){
        $sql = 'delete from `StarPkProduct` where StarPkId = %s';
        $this->query($sql,array($editStarPkModel->Id));
        $starPkProductModel = new \haibao\cms\data\starpk\StarPkProduct();
        $starPkProductModel->addAll($editStarPkModel->StarPkProduct);
    }
    
    public function getStarRandNum($starPkId,$isReturnTotal=true){
    	$cnt = array();
    	if($isReturnTotal){
    		$sql = 'select count(*) as cnt from `StarPkDefine` where Published=1';
    		$result = $this->query($sql)->fetch_assoc();
    		$cnt['totalCnt'] = $result['cnt'];
    	}
    	
    	$sql = 'select count(*) as starCnt from `StarPkDefine` where Published=1 and Id<%s';
    	$result = $this->query($sql,array($starPkId))->fetch_assoc();
    	$cnt['starCnt'] = $result['starCnt'];
		return $cnt;    	
    }
    public function getStarPkUpAndDown($starPkId){
    	 
    	$array = array();
    	$sql = 'select Id from `StarPkDefine` where Id>%s and Published=1 order by Id asc limit 1';
    	$result = $this->query($sql,array($starPkId))->fetch_assoc();
    	$array['upStar'] = isset($result['Id'])?$result['Id']:0;
    	 
    	$sql = 'select Id from `StarPkDefine` where Id<%s and Published=1 order by Id desc limit 1';
    	$result = $this->query($sql,array($starPkId))->fetch_assoc();
    	$array['downStar'] = isset($result['Id'])?$result['Id']:0;
    	return $array;
    }
    
    public function getDataMigrateMap($tableName,$primaryKey,$isOld=false){
    	
    	$str = preg_replace('/(\d+)/', '%s', implode(',', $primaryKey));
		$sql="select OldPrimaryKey,PrimaryKey from DataMigrationMap where ";
		$where = " TableName = %s and PrimaryKey in (".$str.")";
		if($isOld){
			$where = " TableName = %s and OldPrimaryKey in (".$str.")";
		}
		array_unshift($primaryKey, $tableName);
		$result = $this->query($sql.$where, $primaryKey);
		$array = array();
		while ($result->fetch_assoc()){
			$array[$result->getData('PrimaryKey')] = $result->getData('OldPrimaryKey');
		}
		if($isOld){
			$array = array_flip($array);
		}
		return $array;
    }
    
    public function getPastReview($starPkId=0){
    	$sql = "SELECT DATE_FORMAT(PublishTime, '%Y') as ReviewYear FROM StarPkDefine WHERE Id!=".$starPkId." and Published=".\haibao\cms\model\data\starpk\StarPkDefine::PUBLISHED_YES." GROUP BY DATE_FORMAT(PublishTime, '%Y') ORDER BY ReviewYear DESC";
    	$result = $this->query($sql);
    	while($result->fetch_assoc()){
    		if($result->getData('ReviewYear') != '0000'){
    			$reviewDate[$result->getData('ReviewYear')] = array();
    		}
    	}
    	foreach($reviewDate as $key=>$date){
    		$sql = "SELECT DATE_FORMAT(PublishTime, '%m') as ReviewMonth FROM StarPkDefine where DATE_FORMAT(PublishTime, '%Y') = '".$key."' AND Id!=".$starPkId." and Published=".\haibao\cms\model\data\starpk\StarPkDefine::PUBLISHED_YES." GROUP BY DATE_FORMAT(PublishTime, '%m') ORDER BY ReviewMonth DESC";
    		$result = $this->query($sql);
    		while($result->fetch_assoc()){
    			$reviewDate[$key][$result->getData('ReviewMonth')] = preg_replace('/^0/', '', $result->getData('ReviewMonth'));
    		}
    	}
    	return $reviewDate;
    }
}